<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节流</title>
</head>

<body>
    <script>
        function coloring() {
            let r = Math.floor(Math.random() * 255);
            let g = Math.floor(Math.random() * 255);
            let b = Math.floor(Math.random() * 255);
            document.body.style.background = `rgb(${r}, ${g}, ${b})`;
        }
        // 第一种实现方法，使用定时器进行实现
        function throttle_1(func, delay) {
            let timer;
            return function() {
                let context = this;
                let args = arguments;
                if (timer) return;
                timer = setTimeout(function() {
                    func.apply(context, args);
                    timer = null;
                }, delay)
            }    
        }

        // 第二种实现方式，使用时间戳
        function throttle_2(func, delay) {
            let pre = 0;
            return function() {
                let context = this;
                let args = arguments;
                let now = new Date();
                if (now - pre > delay) {
                    func(context, args);
                    pre = now;
                }
            }
        }
        window.addEventListener('resize', throttle_2(coloring, 2000));
    </script>
</body>

</html>